<template>
  <div>
    <el-dialog :model-value="modelValue" title="配置菜单"
               width="800" @close="close">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-position="top" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-tree
                :data="menusTree"
                :props="defaultTreeProps"
                node-key="id"
                show-checkbox
                ref="treeRef"
                style="max-width: 600px"
                @check-change="handleCheckChange"
                @node-click="clickNode"
            />
          </el-col>
          <el-col :span="16">
            <el-checkbox-group v-model="permissionPar">
              <el-checkbox label="增加" value="add" />
              <el-checkbox label="修改" value="edit" />
              <el-checkbox label="查询" value="get" />
              <el-checkbox label="删除" value="delete" />
            </el-checkbox-group>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">{{ "取消" }}</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">{{ "确定" }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { rules} from "./data";
import {ref, watch} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import {AddRole, Bindmenus, getmenus} from "@/api/roles";
import {GetMenus} from "@/api/menus";

const props = defineProps<{
  modelValue: boolean;
  roleId: number;
}>();
const imageUrl = ref('')
const emit = defineEmits(["update:modelValue", "init"]);
const formData = ref<any>({
  roleId: "",
  menus:[]
});

const permissionPar = ref<string[]>([])


const defaultTreeProps = {
  children: 'children',
  label: 'title',
}
const clickNode = (data) => {
  console.log(data)
}
const handleCheckChange = (data: any, checked: boolean) => {
  //切换清除之前的权限
  permissionPar.value = []
  if(checked){
    formData.value.menus.push({
      id:data.id,
      Permissions:[]
    })
    console.log(formData.value.menus)
  }else {
    let delIndex = formData.value.menus.findIndex((_:any) => _.id == data.id)
    if (delIndex > -1) {
      formData.value.menus.splice(delIndex, 1)
      console.log(formData.value.menus)
    }
  }
}

const close = (): void => {
  formData.value = {
    roleId: "",
    menus:[]
  };
  treeRef.value!.setCheckedKeys([], false)
  imageUrl.value = '';
  emit("update:modelValue", false);
  emit("init");

};
const ruleFormRef = ref<FormInstance>();
const submit = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) return;
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      formData.value.roleId = props.roleId
      console.log(formData.value)
      const res = await Bindmenus(formData.value)
      if (res.code == 200) {
        ElMessage.success("操作成功")
        close();
      } else {
        ElMessage.error(res.message)
      }
    }
  });
};

const menusTree = ref<any[]>([])
const init = async () => {
  const res = await GetMenus({});
  if (res.code === 200) {
    menusTree.value = res.data;
  } else {
    menusTree.value = [];
  }
};

const menusId = ref<number[]>([])
const treeRef = ref<any>()
const getRoleMenus = async () => {
  const res = await getmenus({
    roleId: props.roleId,
  })
  if(res.code == 200) {
    menusId.value = res.data
    //设置菜单为勾选状态
    treeRef.value.setCheckedKeys(menusId.value)
  }
}

watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        init();
        getRoleMenus()
      }
    }
)
</script>